<template>
  <div class="test-realtime">
    <div class="header">
      <h2>实时加速度图表测试</h2>
      <div class="status-info">
        <span :class="['status', connectionStatus]">
          {{ connectionStatusText }}
        </span>
        <span class="separator">|</span>
        <span>设备: {{ currentDevice.id }}</span>
        <span class="separator">|</span>
        <span>数据点: {{ dataPointCount }}</span>
      </div>
    </div>

    <div class="controls">
      <el-button-group>
        <el-button
          :type="isWebSocketMode ? 'primary' : 'default'"
          @click="toggleWebSocketMode"
        >
          {{ isWebSocketMode ? 'WebSocket模式' : 'HTTP轮询模式' }}
        </el-button>
        <el-button @click="startSimulation" :disabled="isSimulating">
          开始模拟数据
        </el-button>
        <el-button @click="stopSimulation" :disabled="!isSimulating">
          停止模拟
        </el-button>
        <el-button @click="clearData">清空数据</el-button>
        <el-button @click="runDiagnostics" type="warning">运行诊断</el-button>
        <el-button @click="fixConnection" type="danger">修复连接</el-button>
        <el-button @click="toggleAutoUpdate" :type="autoUpdateEnabled ? 'success' : 'info'">
          {{ autoUpdateEnabled ? '停止自动更新' : '开始自动更新' }}
        </el-button>
      </el-button-group>
    </div>

    <div class="chart-container">
      <div class="chart-header">
        <h3>实时加速度图表</h3>
        <div class="chart-controls">
          <el-radio-group v-model="accelerationType" @change="handleTypeChange">
            <el-radio-button label="rms">RMS</el-radio-button>
            <el-radio-button label="peak">PEAK</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <div id="realtimeChart" class="chart"></div>
    </div>

    <div class="logs">
      <h3>日志信息</h3>
      <div class="log-container">
        <div
          v-for="(log, index) in logs"
          :key="index"
          class="log-item"
          :class="log.type"
        >
          <span class="timestamp">{{ log.timestamp }}</span>
          <span class="message">{{ log.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import DeviceWebSocketService from '../../../utils/websocket'
import AccelerationWindowManager from '../../../utils/accelerationWindowManager'

export default {
  name: 'TestRealtime',
  data() {
    return {
      // WebSocket和数据管理
      webSocketService: null,
      accelerationWindowManager: null,
      isWebSocketMode: true,
      connectionStatus: 'disconnected',

      // 图表相关
      chart: null,
      accelerationType: 'rms',

      // 测试数据
      currentDevice: { id: '30096546', latheName: '测试设备' },
      dataPointCount: 0,
      isSimulating: false,
      simulationTimer: null,
      autoUpdateEnabled: false,
      autoUpdateTimer: null,

      // 日志
      logs: [],
      maxLogs: 50
    }
  },
  computed: {
    connectionStatusText() {
      const statusMap = {
        'connected': '已连接',
        'connecting': '连接中',
        'disconnected': '未连接',
        'error': '连接错误'
      }
      return statusMap[this.connectionStatus] || '未知状态'
    }
  },
  mounted() {
    this.initChart()
    this.initWebSocketAndWindowManager()
  },
  beforeDestroy() {
    this.cleanup()
  },
  methods: {
    /**
     * 初始化图表
     */
    initChart() {
      const chartContainer = document.getElementById('realtimeChart')
      if (!chartContainer) return

      this.chart = echarts.init(chartContainer)

      const option = {
        title: {
          text: '实时加速度数据',
          textStyle: { color: '#fff', fontSize: 14 }
        },
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0,0,0,0.8)',
          textStyle: { color: '#fff' }
        },
        legend: {
          data: ['X轴', 'Y轴', 'Z轴'],
          textStyle: { color: '#fff' }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: [],
          axisLabel: { color: '#fff' },
          axisLine: { lineStyle: { color: '#fff' } }
        },
        yAxis: {
          type: 'value',
          name: this.accelerationType === 'rms' ? 'RMS(m/s²)' : 'PEAK(m/s²)',
          axisLabel: { color: '#fff' },
          axisLine: { lineStyle: { color: '#fff' } },
          splitLine: { lineStyle: { color: 'rgba(255,255,255,0.3)' } }
        },
        series: [
          {
            name: 'X轴',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#ff6b6b' },
            symbol: 'none'
          },
          {
            name: 'Y轴',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#4ecdc4' },
            symbol: 'none'
          },
          {
            name: 'Z轴',
            type: 'line',
            data: [],
            smooth: true,
            lineStyle: { color: '#45b7d1' },
            symbol: 'none'
          }
        ]
      }

      this.chart.setOption(option)
      window.addEventListener('resize', () => this.chart?.resize())
    },

    /**
     * 初始化WebSocket和滑动窗口管理器
     */
    async initWebSocketAndWindowManager() {
      try {
        this.addLog('info', '开始初始化WebSocket和滑动窗口管理器...')

        // 初始化滑动窗口管理器
        this.accelerationWindowManager = new AccelerationWindowManager({
          windowSize: 60,
          updateInterval: 1000,
          onDataUpdate: (data) => {
            this.handleWindowDataUpdate(data)
          },
          onError: (error) => {
            this.addLog('error', `滑动窗口错误: ${error.message}`)
          }
        })

        this.accelerationWindowManager.start()
        this.addLog('success', '滑动窗口管理器启动成功')

        // 初始化WebSocket
        if (this.isWebSocketMode) {
          await this.initWebSocket()
        }

      } catch (error) {
        this.addLog('error', `初始化失败: ${error.message}`)
      }
    },

    /**
     * 初始化WebSocket
     */
    async initWebSocket() {
      try {
        this.connectionStatus = 'connecting'
        this.addLog('info', '正在连接WebSocket...')

        this.webSocketService = new DeviceWebSocketService()
        this.setupWebSocketListeners()

        const wsUrl = process.env.VUE_APP_WS_URL || 'ws://localhost:8081/ws/device-monitor'
        await this.webSocketService.connect(wsUrl)

      } catch (error) {
        this.connectionStatus = 'error'
        this.addLog('error', `WebSocket连接失败: ${error.message}`)
      }
    },

    /**
     * 设置WebSocket监听器
     */
    setupWebSocketListeners() {
      if (!this.webSocketService) return

      this.webSocketService.on('connected', () => {
        this.connectionStatus = 'connected'
        this.addLog('success', 'WebSocket连接成功')

        // 订阅设备数据
        this.webSocketService.subscribeAccelerationData(
          this.currentDevice.id,
          this.currentDevice.latheName
        )
      })

      this.webSocketService.on('disconnected', () => {
        this.connectionStatus = 'disconnected'
        this.addLog('warning', 'WebSocket连接断开')
      })

      this.webSocketService.on('accelerationDataUpdate', (data) => {
        this.handleWebSocketData(data)
      })

      this.webSocketService.on('error', (error) => {
        this.connectionStatus = 'error'
        this.addLog('error', `WebSocket错误: ${error.message}`)
      })
    },

    /**
     * 处理WebSocket数据
     */
    handleWebSocketData(data) {
      if (!data || data.deviceId !== this.currentDevice.id) return

      this.addLog('info', `收到WebSocket数据: ${data.deviceId}`)

      // 传递给滑动窗口管理器
      if (this.accelerationWindowManager) {
        this.accelerationWindowManager.addAccelerationData({
          deviceId: data.deviceId,
          latheName: data.latheName,
          accelerationData: {
            rms: {
              x: data.xrms || 0,
              y: data.yrms || 0,
              z: data.zrms || 0
            },
            peak: {
              x: data.xpeak || 0,
              y: data.ypeak || 0,
              z: data.zpeak || 0
            }
          },
          timestamp: data.timestamp || Date.now()
        })
      }
    },

    /**
     * 处理滑动窗口数据更新
     */
    handleWindowDataUpdate(data) {
      if (!data || !data.data) return

      this.dataPointCount = data.data.timeData.length
      this.updateChart(data.data)
      this.addLog('info', `图表数据已更新: ${data.deviceId}`)
    },

    /**
     * 更新图表
     */
    updateChart(windowData) {
      if (!this.chart || !windowData) return

      const currentData = this.accelerationType === 'rms' ? windowData.rms : windowData.peak

      const option = {
        xAxis: {
          data: windowData.timeData
        },
        series: [
          { data: currentData.x },
          { data: currentData.y },
          { data: currentData.z }
        ]
      }

      this.chart.setOption(option)
    },

    /**
     * 切换WebSocket模式
     */
    async toggleWebSocketMode() {
      this.isWebSocketMode = !this.isWebSocketMode

      if (this.isWebSocketMode) {
        await this.initWebSocket()
      } else {
        this.disconnectWebSocket()
      }
    },

    /**
     * 断开WebSocket
     */
    disconnectWebSocket() {
      if (this.webSocketService) {
        this.webSocketService.disconnect()
        this.webSocketService = null
        this.connectionStatus = 'disconnected'
        this.addLog('info', 'WebSocket已断开')
      }
    },

    /**
     * 开始数据模拟
     */
    startSimulation() {
      if (this.isSimulating) return

      this.isSimulating = true
      this.addLog('info', '开始数据模拟')

      if (this.accelerationWindowManager) {
        this.simulationTimer = this.accelerationWindowManager.simulateData(
          this.currentDevice.id,
          this.currentDevice.latheName
        )
      }
    },

    /**
     * 停止数据模拟
     */
    stopSimulation() {
      this.isSimulating = false

      if (this.simulationTimer) {
        clearInterval(this.simulationTimer)
        this.simulationTimer = null
      }

      this.addLog('info', '数据模拟已停止')
    },

    /**
     * 清空数据
     */
    clearData() {
      if (this.accelerationWindowManager) {
        this.accelerationWindowManager.clearAllData()
      }

      this.dataPointCount = 0
      this.addLog('info', '数据已清空')
    },

    /**
     * 处理加速度类型变化
     */
    handleTypeChange() {
      this.addLog('info', `切换到${this.accelerationType}模式`)

      // 更新图表Y轴标签
      if (this.chart) {
        this.chart.setOption({
          yAxis: {
            name: this.accelerationType === 'rms' ? 'RMS(m/s²)' : 'PEAK(m/s²)'
          }
        })
      }
    },

    /**
     * 添加日志
     */
    addLog(type, message) {
      const log = {
        type,
        message,
        timestamp: new Date().toLocaleTimeString()
      }

      this.logs.unshift(log)

      if (this.logs.length > this.maxLogs) {
        this.logs = this.logs.slice(0, this.maxLogs)
      }
    },

    /**
     * 运行诊断
     */
    runDiagnostics() {
      this.addLog('info', '开始运行WebSocket诊断...')

      // 检查基础环境
      const wsSupported = 'WebSocket' in window
      this.addLog(wsSupported ? 'success' : 'error', `WebSocket支持: ${wsSupported}`)

      // 检查连接状态
      if (this.webSocketService) {
        const state = this.webSocketService.getConnectionState()
        this.addLog('info', `连接状态: ${JSON.stringify(state)}`)
      } else {
        this.addLog('warning', 'WebSocket服务未初始化')
      }

      // 检查滑动窗口管理器
      if (this.accelerationWindowManager) {
        const status = this.accelerationWindowManager.getStatus()
        this.addLog('info', `窗口管理器状态: ${JSON.stringify(status)}`)
      } else {
        this.addLog('warning', '滑动窗口管理器未初始化')
      }

      // 检查图表
      if (this.chart) {
        this.addLog('success', '图表实例正常')
      } else {
        this.addLog('error', '图表实例未找到')
      }

      this.addLog('info', '诊断完成')
    },

    /**
     * 修复连接
     */
    async fixConnection() {
      this.addLog('info', '开始修复WebSocket连接...')

      try {
        // 清理现有连接
        this.disconnectWebSocket()

        if (this.accelerationWindowManager) {
          this.accelerationWindowManager.stop()
          this.accelerationWindowManager = null
        }

        this.addLog('success', '已清理现有连接')

        // 重新初始化
        await this.initWebSocketAndWindowManager()
        this.addLog('success', '重新初始化完成')

        // 等待连接建立
        setTimeout(() => {
          if (this.connectionStatus === 'connected') {
            this.addLog('success', '连接修复成功！')
            this.startSimulation()
          } else {
            this.addLog('error', '连接修复失败，请检查后端服务')
          }
        }, 2000)

      } catch (error) {
        this.addLog('error', `修复失败: ${error.message}`)
      }
    },

    /**
     * 切换自动更新
     */
    toggleAutoUpdate() {
      if (this.autoUpdateEnabled) {
        this.stopAutoUpdate()
      } else {
        this.startAutoUpdate()
      }
    },

    /**
     * 开始自动更新
     */
    startAutoUpdate() {
      if (this.autoUpdateTimer) {
        clearInterval(this.autoUpdateTimer)
      }

      this.autoUpdateEnabled = true
      this.addLog('success', '开始自动更新模式')

      // 每秒生成新数据
      this.autoUpdateTimer = setInterval(() => {
        if (this.accelerationWindowManager) {
          const mockData = {
            deviceId: this.currentDevice.id,
            latheName: this.currentDevice.latheName,
            accelerationData: {
              rms: {
                x: Math.random() * 5 + 1,
                y: Math.random() * 5 + 1,
                z: Math.random() * 5 + 1
              },
              peak: {
                x: Math.random() * 10 + 2,
                y: Math.random() * 10 + 2,
                z: Math.random() * 10 + 2
              }
            },
            timestamp: Date.now()
          }

          this.accelerationWindowManager.addAccelerationData(mockData)
          this.addLog('info', `自动更新数据: ${new Date().toLocaleTimeString()}`)
        }
      }, 1000)
    },

    /**
     * 停止自动更新
     */
    stopAutoUpdate() {
      if (this.autoUpdateTimer) {
        clearInterval(this.autoUpdateTimer)
        this.autoUpdateTimer = null
      }

      this.autoUpdateEnabled = false
      this.addLog('warning', '自动更新已停止')
    },

    /**
     * 清理资源
     */
    cleanup() {
      this.stopSimulation()
      this.stopAutoUpdate()
      this.disconnectWebSocket()

      if (this.accelerationWindowManager) {
        this.accelerationWindowManager.stop()
      }

      if (this.chart) {
        this.chart.dispose()
      }

      window.removeEventListener('resize', () => this.chart?.resize())
    }
  }
}
</script>

<style lang="scss" scoped>
.test-realtime {
  padding: 20px;
  background: #0a1628;
  color: #fff;
  min-height: 100vh;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);

    h2 {
      margin: 0;
      color: #fff;
    }

    .status-info {
      display: flex;
      align-items: center;
      gap: 10px;
      font-size: 14px;

      .status {
        padding: 4px 12px;
        border-radius: 4px;
        font-weight: bold;

        &.connected {
          background: rgba(76, 175, 80, 0.2);
          color: #4caf50;
        }

        &.connecting {
          background: rgba(255, 193, 7, 0.2);
          color: #ffc107;
        }

        &.disconnected {
          background: rgba(158, 158, 158, 0.2);
          color: #9e9e9e;
        }

        &.error {
          background: rgba(244, 67, 54, 0.2);
          color: #f44336;
        }
      }

      .separator {
        color: rgba(255, 255, 255, 0.3);
      }
    }
  }

  .controls {
    margin-bottom: 20px;
  }

  .chart-container {
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;

    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      h3 {
        margin: 0;
        color: #fff;
      }
    }

    .chart {
      width: 100%;
      height: 400px;
    }
  }

  .logs {
    background: rgba(3, 12, 49, 0.6);
    border: 1px solid rgba(28, 89, 156, 0.3);
    border-radius: 8px;
    padding: 20px;

    h3 {
      margin: 0 0 15px 0;
      color: #fff;
    }

    .log-container {
      max-height: 300px;
      overflow-y: auto;
      background: rgba(0, 0, 0, 0.3);
      border-radius: 4px;
      padding: 10px;

      .log-item {
        display: flex;
        gap: 10px;
        padding: 5px 0;
        border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        font-size: 12px;

        &:last-child {
          border-bottom: none;
        }

        .timestamp {
          color: rgba(255, 255, 255, 0.6);
          min-width: 80px;
        }

        .message {
          flex: 1;
        }

        &.info .message {
          color: #2196f3;
        }

        &.success .message {
          color: #4caf50;
        }

        &.warning .message {
          color: #ff9800;
        }

        &.error .message {
          color: #f44336;
        }
      }
    }
  }
}

// Element UI 样式覆盖
::v-deep .el-button-group .el-button {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.3);
  color: #fff;

  &:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.5);
  }

  &.el-button--primary {
    background: rgba(64, 158, 255, 0.8);
    border-color: #409eff;
  }
}

::v-deep .el-radio-button__inner {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.3);
  color: #fff;

  &:hover {
    background: rgba(255, 255, 255, 0.2);
  }
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background: rgba(64, 158, 255, 0.8);
  border-color: #409eff;
  color: #fff;
}
</style>
